//
//  ViewController.m
//  WXPay
//
//  Created by Burn on 2019/2/17.
//  Copyright © 2019 nmgxysh. All rights reserved.
//

#import "ViewController.h"
#import "WXApi.h"
// 获取IP
#import <ifaddrs.h>
#import <arpa/inet.h>

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
}
- (IBAction)payClick:(id)sender {
    //  通过自己后台请求订单信息
    //  1参数
    NSMutableDictionary *parameter = [NSMutableDictionary dictionary];
    parameter[@"orderid"] = [self generateTradeNO];
    parameter[@"userIp"] = [self deviceIPAdress];
    
    //  2发送请求
    NSURLSession *session = [NSURLSession sharedSession];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"URL"]];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [NSJSONSerialization dataWithJSONObject:parameter options:NSJSONWritingPrettyPrinted error:nil];
    //创建任务Task
   __block NSMutableDictionary *responseDict  = [NSMutableDictionary dictionary];
//    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//        responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
//    }];
//    [task resume];
    
    //  3订单信息
    [WXApi registerApp:[responseDict objectForKey:@"appid"]];
    PayReq *rep = [[PayReq alloc]init];
    rep.partnerId = [responseDict objectForKey:@"mch_id"];  // 商家向财付通申请的商家id
    rep.prepayId = [responseDict objectForKey:@"prepay_id"]; // 支付订单
    rep.package = @"Sign=WXPay";  // Sign=WXPay 商家根据财付通文档填写的数据和签名
    rep.nonceStr = [responseDict objectForKey:@"nonce_str"]; // 随机串，防重发
    rep.timeStamp = [[responseDict objectForKey:@"timestamp"] intValue]; // 时间戳，防重发
    rep.sign = [responseDict objectForKey:@"sign2"]; // 商家根据微信开放平台文档对数据做的签名 二次签名
    
    //  3 BOOL = [WXApi sendReq:rep] 会切换到微信的界面。第三方应用程序等待微信返回onResp。微信在异步处理完成后一定会调用onResp。
    if ([WXApi sendReq:rep]) {
        //  这里的通知在
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(succeed) name:@"WeChatPaySucceed" object:nil];
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(fail) name:@"WeChatPayFail" object:nil];
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"支付失败" message:@"未安装微信客户端,请使用其他支付方式" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}
#pragma mark - succeed
- (void)succeed{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"测试" message:@"支付成功" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - fail
- (void)fail{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"测试" message:@"支付失败" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}



#pragma mark - 订单ID（由商家自行制定）
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand((unsigned)time(NULL));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}
#pragma mark - 获取用户IP
- (NSString *)deviceIPAdress {
    NSString *address = @"an error occurred when obtaining ip address";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    success = getifaddrs(&interfaces);
    
    if (success == 0) { // 0 表示获取成功
        
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    freeifaddrs(interfaces);
    
    NSLog(@"手机设备的IP是：%@", address);
    return address;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
